<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

namespace moonpie\plugin\wechat_account\validate;


use Monolog\Logger;
use think\Validate;

class LoggingTypeValidator extends Validate
{
    protected  $rule = [
        'loggingType' => 'require|validLogTypes',
        'loggingData' => 'validLogData',
        'level' => 'require|validLogLevels',
        'path' => 'require|validLogPath',
        'days' => 'require|integer|gt:0',
    ];
    protected $field = [
        'loggingType' => '日志类型',
        'loggingData' => '日志配置',
        'path' => '日志文件',
        'level' => '日志级别',
        'days' => '间隔天数',
    ];
    protected $scene = [
        'init' => [
            'loggingType', 'loggingData',
        ],
        'single' => ['level', 'path'],
        'daily' => ['level', 'path', 'days'],
    ];
    protected $currentScene = 'init';
    protected function validLogPath($path, $rule, $data, $field, $title)
    {
        return true;
    }
    protected function validLogLevels($level, $rule, $data, $field, $title)
    {
        $label = "{$field}.validLogLevels";
        $levels = Logger::getLevels();
        if(!isset($levels[strtoupper($level)])) {
            $this->message($label, "{$level}不是可以使用的{$title}");
            return false;
        }
        return true;
    }
    protected function validLogTypes($type, $rule, $data, $field, $title)
    {
        $label = "{$field}.validLogTypes";
        if(!in_array($type, $this->getValidLogTypes())){
            $this->message($label, "{$title}的数据'{$type}'不是支持的日志类型");
            return false;
        }
        return true;
    }
    protected function getValidLogTypes()
    {
        return ['single', 'daily'];
    }
    protected function validLogData($log, $rule, $data, $field, $title)
    {
        $label = "{$field}.validLogData";
        switch ($data['loggingType']) {
            case 'single':
            case 'daily':
                $validator = new static();
                $result = $validator->scene($data['loggingType'])->check($log);
                if(!$result) {
                    $this->message($label, "{$title}存在错误配置信息：{$validator->getError()}");
                    return false;
                }
                return true;
            default:
                $this->message($label, "{$title}验证失败");
                return false;

        }
    }
}